import { defineStore } from 'pinia'
import { useOsTheme } from 'naive-ui'
import dayjs from '@/common/dayjs'
import { useNaive } from './useNaive'
import { useI18n } from 'vue-i18n'

export const useUserSettings = defineStore('userSettings', {
	persist: true,
	state() {
		/** 用户设置 */
		return {
			isDark: undefined,
			locale: 'zhCN',
			isCollapsedSidebar: false
		} as UserSettings
	},
	actions: {
		/** 初始化用户设置 */
		init() {
			this.initSettings()
			this.watchSettings()
		},
		/** 初始化用户设置 */
		initSettings() {
			const userSettingsJSON = localStorage.getItem('userSettings') || '{}'
			const userSettingsStorage: UserSettings = JSON.parse(userSettingsJSON)
			this.$patch(userSettingsStorage)
			this.initDarkSetting()
		},
		/** 监听所有用户设置 */
		watchSettings() {
			this.watchIsDark()
			this.watchLocale()
		},
		/** 初始化黑暗模式设置 */
		initDarkSetting() {
			// isDark 为 undefined，代表用户从未设置是否黑暗模式，则判断用户系统是否开启黑暗模式
			if (this.isDark === undefined) {
				const osTheme = useOsTheme()
				this.isDark = osTheme.value === 'dark'
			}
		},
		/** 监听黑暗模式改变navie主题 */
		watchIsDark() {
			const naive = useNaive()
			watch(
				() => this.isDark,
				async isDark => {
					if (isDark) {
						const { darkTheme } = await import('naive-ui')
						naive.config.theme = darkTheme
					} else {
						const { lightTheme } = await import('naive-ui')
						naive.config.theme = lightTheme
					}
				},
				{ immediate: true }
			)
		},
		/** 监听语言环境设置 */
		watchLocale() {
			const i18n = useI18n()
			const naive = useNaive()
			watch(
				() => this.locale,
				async locale => {
					const htmlEl = document.querySelector('html')
					switch (locale) {
						case 'zhCN': {
							htmlEl!.setAttribute('lang', 'zh')
							i18n.locale.value = 'zhCN'
							const { zhCN, dateZhCN } = await import('naive-ui')
							naive.config.locale = zhCN
							naive.config.dateLocale = dateZhCN
							await import('dayjs/locale/zh-cn')
							dayjs.locale('zh-cn')
							break
						}
						case 'enUS': {
							htmlEl!.setAttribute('lang', 'en')
							i18n.locale.value = 'enUS'
							const { enUS, dateEnUS } = await import('naive-ui')
							naive.config.locale = enUS
							naive.config.dateLocale = dateEnUS
							await import('dayjs/locale/en')
							dayjs.locale('en')
							break
						}
						default: {
							// eslint-disable-next-line no-console
							console.warn(`locale 值应为 zhCN | enUS, 但这里为${locale}`)
						}
					}
				},
				{ immediate: true }
			)
		}
	}
})
